import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const isLogin = ref(localStorage.getItem('isLogin') === 'true')
  const role = ref(localStorage.getItem('role') || '')
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))

  function login(userRole, userInfo = null) {
    isLogin.value = true
    role.value = userRole
    
    // 设置默认用户信息
    if (userInfo) {
      user.value = userInfo
    } else {
      // 根据角色设置默认用户信息
      const defaultUserInfo = {
        name: getDefaultUserName(userRole),
        avatar: '/avatar.png',
        role: userRole
      }
      user.value = defaultUserInfo
    }
    
    localStorage.setItem('isLogin', 'true')
    localStorage.setItem('role', userRole)
    localStorage.setItem('user', JSON.stringify(user.value))
  }

  function logout() {
    isLogin.value = false
    role.value = ''
    user.value = null
    localStorage.removeItem('isLogin')
    localStorage.removeItem('role')
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    window.dispatchEvent(new Event('logout'))
  }

  function updateUserInfo(userInfo) {
    user.value = { ...user.value, ...userInfo }
    localStorage.setItem('user', JSON.stringify(user.value))
  }

  function getDefaultUserName(role) {
    const roleNames = {
      'student': '学生',
      'teacher': '教师',
      'admin': '管理员'
    }
    return roleNames[role] || '用户'
  }

  return { 
    isLogin, 
    role, 
    user, 
    login, 
    logout, 
    updateUserInfo 
  }
}) 